import lotus from './lotus/lotus'

export function throttle (fn, interval = 300) {
  let canRun = true
  return function () {
    if (!canRun) return
    canRun = false
    setTimeout(() => {
      fn.apply(this, arguments)
      canRun = true
    }, interval)
  }
}

export function debounce (func, ms = 300) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, ms)
  }
}

/**
 * html的实体字符转义成原本的字符
 * @param {String} str
 * @return {String}
 */
export const decodeHtml = (str) => {
  let s = ''
  if (!str || str.length === 0) return ''
  s = str.replace(/&amp;/g, '&')
  s = s.replace(/&lt;/g, '<')
  s = s.replace(/&gt;/g, '>')
  s = s.replace(/&nbsp;/g, ' ')
  s = s.replace(/&#39;/g, "'")
  s = s.replace(/&quot;/g, '"')
  return s
}

export const replaceProtocol = (url) => {
  return url ? url.replace(/^(http(s)?:)/, '') : ''
}

/**
 * 计算比例函数
 * @param {Number} num 分子
 * @param {Number} deno 分母
 * @param {Number} decimal 保留小数位
 * @return {String}
 */
export const calcRate = (num, deno, decimal) => {
  if (+deno === 0) {
    return ''
  }
  return `${parseFloat((+num * 100 / +deno).toFixed(decimal))}%`
}

/**
 * 获取指定名称的COOKIE的值
 * @param {string} cookieName
 * @returns cookie值
 */
export const getCookie = (cookieName) => {
  if (!cookieName) {
    return ''
  }
  const allcookies = document.cookie
  let value = ''
  let cookiePos = allcookies.indexOf(cookieName)
  if (cookiePos !== -1) {
    cookiePos = cookiePos + cookieName.length + 1
    let cookieEnd = allcookies.indexOf(';', cookiePos)
    if (cookieEnd === -1) {
      cookieEnd = allcookies.length
    }
    value = decodeURIComponent(allcookies.substring(cookiePos, cookieEnd))
  }
  return value
}

/**
 * 判断传参不为空
 * @param {any} value 传参
 * @returns 是否不为空（不是null 且 不是undefined 且 不是空字符串）
 */
export const isNotEmpty = (value) => {
  return value !== null && value !== undefined && value !== ''
}

// 通过链接下载文件
export const fileDownLoad = (fileUrl, fileName) => {
  // 创建一个虚拟的a标签
  const link = document.createElement('a')
  // 设置a标签的href为PDF文件的路径
  link.href = fileUrl
  // 设置下载属性，指定下载文件的名称
  link.download = fileName || 'document.text'
  // 兼容性处理：如果是iOS设备，则使用window.open来触发下载
  if (lotus.isIos) {
    lotus.navigator.forward({ url: fileUrl, useSysBrowser: 1 })
  } else {
    // 将虚拟a标签添加到DOM中
    document.body.appendChild(link)
    // 触发点击事件，开始下载
    link.click()
    // 下载完成后移除虚拟a标签
    document.body.removeChild(link)
  }
}
